package servlet;

import bean.House_info;
import bean.House_type;
import util.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String sql="select * from house_type";

        ResultSet rs = DBUtil.select(sql);
        ArrayList<Object> list = new ArrayList<>();
        try {
            while (rs.next()){
                int id = rs.getInt("id");
                String type = rs.getString("type");

                House_type houseType = new House_type(id, type);
                list.add(houseType);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(list);
        request.setAttribute("list",list);
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String leaseMode = request.getParameter("leaseMode");
        String rent = request.getParameter("rent");
        String contacts = request.getParameter("contacts");
        String depositmethod = request.getParameter("depositmethod");
        String typeId = request.getParameter("typeId");
        String address = request.getParameter("address");

        String sql="insert into house_info values(?,?,?,?,?,?,?)";

       int i = DBUtil.update(sql,null,leaseMode,rent,contacts,depositmethod,typeId,address);

        if (i>0) {
            response.sendRedirect("/list");
        }else {
            request.setAttribute("msg","添加失败");
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
        }
    }

}
